﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace StatlightTfsBuildIntegration.Statlight
{
	public static class TestBuilder
	{
		public static TestRun Parse(string filename)
		{
			XDocument document = XDocument.Load(filename);

			var root = document.Element("StatLightTestResults");

			var testRun = new TestRun();
			testRun.Name = "StatLight Test run";
			testRun.StartTime = DateTime.Parse(root.Attribute("dateRun").Value);

			testRun.TestCount = int.Parse(root.Attribute("total").Value);
			testRun.TestFailed = int.Parse(root.Attribute("failed").Value);
			testRun.TestSkipped = int.Parse(root.Attribute("ignored").Value);
			testRun.TestSuccessed = testRun.TestCount - testRun.TestFailed - testRun.TestSkipped;

			List<Test> testList = new List<Test>();
			foreach( var x in root.Descendants("test"))
			{
				var test = new Test
				{
					Name = x.Attribute("name").Value,
					Result = Map(x.Attribute("resulttype").Value),
					Time = TimeSpan.Parse(x.Attribute("timeToComplete").Value)
				};
				if (test.Result == TestResult.Fail)
				{
					var exceptionInfo = x.Element("exceptionInfo");
					if (exceptionInfo != null)
					{
						var message = exceptionInfo.Element("message");
						if (message != null)
							test.Message = message.Value;

						var stackTrace = exceptionInfo.Element("stackTrace");
						if (stackTrace != null)
							test.StackTrace = stackTrace.Value;


					}
				}
				testList.Add(test);
			}
			testRun.TestList = testList;
			return testRun;
		}

		private static TestResult Map(string text)
		{
			if (text == "Passed")
				return TestResult.Pass;
			if (text == "Failed")
				return TestResult.Fail;

			return TestResult.Unknown;
		}
	}
}
